package exchange.core;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

public class Mail implements Runnable {
	private static Logger log = Logger.getLogger(Mail.class.getName());
	private ObjectOutputStream out;
	String msg;
	private static final int NTHREDS = 10;
	private static ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); 
	
	public static void send(ObjectOutputStream out, String msg){
		executor.execute( new Mail (out, msg) ) ;
	}

	private Mail (ObjectOutputStream out, String msg){
		this.out = out;
		this.msg = msg;
	}
	
	@Override
	public void run() {
		sendMail(msg);
	}
	
	private void sendMail(final String msg) {
		synchronized (out) {
			try {
				out.writeObject(msg);
				out.flush();
			} catch (SocketException socketeExc){
				log.warning("socket is closed");
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}
	
}
